<template>
  <div class="zh-livePlay-list">
    <nav-header></nav-header>
    <div class="zh-table">
      <div class="zh-table-open clear">
        <div class="zh-open-left fl">
          <div class="open-width" style="width: 150px" v-if="$store.state.checkLevel">
            <el-select v-if="$store.state.platformInformation" v-model="platform_id" filterable placeholder="教育局/学校">
              <el-option v-for="item in schoolcodeData" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
            <el-cascader placeholder="组织架构选择" v-else v-model="valueData" :options="orgDlist" :props="optionProps"
              @change="handleChange(valueData)"></el-cascader>
          </div>
          <div class="open-width" style="width: 110px">
            <!-- v-if="!$store.state.checkLevel" -->
            <el-select v-model="live_type" filterable placeholder="请选择">
              <el-option v-for="item in liveOptons" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="open-width">
            <el-date-picker v-model="dataTime" value-format="yyyy-MM-dd" type="daterange" align="left" unlink-panels
              range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
            </el-date-picker>
          </div>
          <div class="open-width">
            <el-input v-model="keyword" placeholder="直播名称、主讲人" @keyup.enter.native="searchFunc"></el-input>
          </div>
          <el-button type="primary" @click="searchFunc">搜索</el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </div>
        <div class="zh-open-right fr">
          <el-button type="text" v-if="$store.state.checkLevel && app_code !== '00000000000000000000000000000000'"
            @click="toLink('/resources/live/live-push-history')">推送历史</el-button>
          <el-button type="primary" v-if="!$store.state.checkLevel" @click="importClass()">从课表导入</el-button>
          <el-button type="primary" @click="broadcast()">预约直播</el-button>
          <el-button type="danger" v-if="$store.state.checkLevel" @click="delAllLiveplay">批量删除</el-button>
        </div>
      </div>
      <div class="zh-table-contents" v-loading="loading.status" :element-loading-text="loading.txt">
        <el-table v-if="$store.state.checkLevel" :data="listData" border max-height="600"
          @selection-change="handleSelectionChange" style="width: 100%">
          <el-table-column align="center" type="selection" show-overflow-tooltip width="50">
          </el-table-column>
          <el-table-column prop="name" label="直播名称" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="category" label="直播分类" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="teachername" label="主讲人" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="" label="直播教室" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.cl_name ? scope.row.cl_name : "-" }}
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="直播时间" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="_status_text" label="状态" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="5" label="操作" align="center" width="280">
            <template slot-scope="scope">
              <el-button v-if="scope.row._status != 2" @click="
                toLink('/resources/live/live-details?id=' + scope.row.id)
              " type="text">查看</el-button>
              <el-button v-if="scope.row._status == 2" @click="videoView(scope.row)" type="text">预览</el-button>
              <el-button v-show="!isTopEducation" v-if="scope.row._status == 1" @click="pushUpTrigger(scope.row)"
                type="text">推上级</el-button>
              <!-- 	<el-button v-if="scope.row._status == 2" @click="toLink('/resources/live/live-details?id=' + scope.row.id)" type="text">预览</el-button> -->
              <el-button v-if="scope.row._status == 2" @click="stopConfirm(scope.row)" type="text"
                class="delete-button">停止</el-button>
              <el-button v-if="scope.row._status == 3" @click="
                toLink('/resources/live/live-statistics?id=' + scope.row.id)
              " type="text">直播统计</el-button>
              <el-button @click="delete_confirm(scope.row)" type="text" class="delete-button">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-table v-else :data="listData" border max-height="600" style="width: 100%">
          <el-table-column type="index" :index="typeIndex" label="序号" align="center" show-overflow-tooltip width="50">
          </el-table-column>
          <el-table-column prop="name" label="直播名称" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="subjectname" label="课程分类" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="teachername" label="主讲人" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="" label="直播教室" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.cl_name ? scope.row.cl_name : "-" }}
            </template>
          </el-table-column>
          <el-table-column prop="recorder_name" label="直播设备" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="duration" label="直播时间" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="_status_text" label="直播状态" align="center" show-overflow-tooltip>
          </el-table-column>
          <!-- <el-table-column
                        prop=""
                        label="是否加密"
                        align="center"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
			      			{{scope.row.password ? '是' : '否'}}
			      	    </template>
				    </el-table-column> -->
          <el-table-column prop="" label="直播密码" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.password ? scope.row.password : "-" }}
            </template>
          </el-table-column>
          <el-table-column prop="" label="是否录制" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.is_record ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column prop="5" label="操作" align="center" width="300">
            <template slot-scope="scope">
              <el-button @click="foundRtsp(scope.row)" type="text">流地址</el-button>
              <el-button @click="
                toLink('/resources/live/live-details?id=' + scope.row.id)
              " type="text">查看</el-button>
              <el-button v-if="scope.row._status == 2" @click="videoView(scope.row)" type="text">预览</el-button>
              <el-button @click="
                toLink('/resources/live/live-statistics?id=' + scope.row.id)
              " type="text">直播统计</el-button>
              <!-- <template v-if="$store.state.checkLevel">
                <el-button
                  v-if="platform && scope.row._status !== 3"
                  @click="pushUpTrigger(scope.row)"
                  type="text"
                  >推上级</el-button
                >
                <el-button
                  v-if="
                    $store.state.platformInformation && scope.row._status !== 3
                  "
                  @click="pushLow(scope.row)"
                  type="text"
                  >推下级</el-button
                >
              </template> -->
              <el-button v-if="scope.row._status == 2" @click="stopConfirm(scope.row)" type="text"
                class="delete-button">停止</el-button>
              <el-button @click="delete_confirm(scope.row)" type="text" class="delete-button">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="table-pagination" v-show="total_number > 10">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="listParam.page_index" :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size="listParam.page_size" layout="total, sizes, prev, pager, next, jumper" :total="total_number">
          </el-pagination>
          <div class="pagination-button">
            <el-button @click="getList" type="primary" icon="el-icon-refresh" circle title="刷新数据" size="mini">
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <!-- 推下级begin -->
    <el-dialog title="推下级" :visible.sync="pushLowFlag" v-if="pushLowFlag" width="600px" :close-on-click-modal="false">
      <push-low-win @listenPushLow="getPushLowList"></push-low-win>
      <span slot="footer" class="dialog-footer">
        <el-button @click="pushActive()">取 消</el-button>
        <el-button type="primary" @click="pushActive(1)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 推下级end -->
    <transition name="el-fade-in-linear">
      <div class="masking" :class="{ activeLive: isActive }">
        <div class="maskingBox">
          <div class="masking_h">
            <span>直播预览</span>
            <i class="el-icon-close" @click="viewClose"></i>
          </div>
          <div class="masking_cc">
            <!-- <flvPlayer
            v-if="showVideoPlayer"
              id="flvPlayer"
              :playerOption.sync="playerOption"
            ></flvPlayer> -->

            <flvdplayer v-if="showVideoPlayer" :playerOption.sync="playerOption"></flvdplayer>

            <!-- v-if="showVideoPlayer && !webrtc" <webRtcPlayer v-else  :url="'webrtc://192.168.5.83/live/dep10'" :uid="`${Math.random()}`"></webRtcPlayer> -->
          </div>
        </div>
      </div>
    </transition>

    <el-dialog title="直播流地址" :visible.sync="foundRtspFlag" width="400px" :close-on-click-modal="false"
      @close="handleClose">
      <p ref="rtspText" class="rtspText">{{ adress }}</p>
      <textarea ref="copyText" class="copyText">这是幕后黑手</textarea>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="noCopy()">取 消</el-button>
        <el-button type="primary" @click="copyRstp()">复制地址</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import pushLowWin from "@/components/common/push-low-win";
// import flvPlayer from "../../public/flvPlayer";
import flvdplayer from "@/components/public/flvdplayer";
import webRtcPlayer from '@/components/common/webrtcPlayer'
export default {
  data() {
    return {
      adress: '',
      foundRtspFlag: false,
      orgDlist: [], // 学段数据
      valueData: [], // 学段/年级/科目id
      optionProps: {
        value: "grade_id",
        label: "name",
      },
      app_code: sessionStorage.getItem("CheckSchoolAppCode"),
      isTopEducation: sessionStorage.getItem('CheckSchoolAppCode') === '00000000000000000000000000000000',
      loading: {
        status: false,
        txt: "获取数据...",
      },
      liveOptons: [
        { value: "-1", label: "选择状态" },
        { value: "1", label: "未开始" },
        { value: "2", label: "进行中" },
        { value: "3", label: "已结束" },
      ],
      listParam: {
        platform_id: undefined,
        live_type: "-1",
        keyword: undefined,
        page_index: 1,
        page_size: 10,
      },
      live_type: "-1",
      keyword: "",
      dataTime: [],
      total_number: 0,
      listData: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      platform_id: null,
      schoolcodeData: [],
      /**存放学校教育局列表 */
      platformList: [],
      /*学校/教育局列表 */
      platform: "",
      /*可推送上级 */
      pid: "",
      /*可推送上级id */
      pushLowFlag: false,
      /*推下级弹窗 */
      pushLowObj: null,
      /*推下级对象 */
      pushLowNames: ["1", "2"],
      /*获取下级列表参数 */
      schoolList: [],
      /*学校列表 */
      selSchoolList: [],
      /*选择的下级列表 */
      ids: [],
      /*存放被选中的视频列表 */
      pushLowStatus: null,
      /*记录是否批量推下级*/
      pushUpStatus: null,
      /*记录是否批量推上级 */
      isActive: true,
      showVideoPlayer: false,
      playerOption: {
        type: "flv",
        url: "",
        status_stream: true,
        status_stream_audio: true
      },
    };
  },
  created() {
    this.getOrgnk();
    this.get_schoolcode();
    this.getList();
    if (this.$store.state.checkLevel) {
      this.platform_parent();
    }
  },
  computed: {
    webrtc() {
      return this.$store.getters.isSupportWebRtc;
    },
    allownine() {
      return this.$store.getters.isAllowNine;
    }
  },
  methods: {
    foundRtsp(obj) { // 点击流地址弹出弹窗
      !this.webrtc && (this.adress = obj.rtmp)
      this.webrtc && (this.adress = obj.webrtc_url)

      this.foundRtspFlag = true
    },
    copyRstp() { // 复制流地址
      this.$refs.copyText.value = this.$refs.rtspText.innerText
      this.$refs.copyText.select()
      document.execCommand("copy")
      this.$message.success('复制成功')
    },
    noCopy() { // 取消复制关闭弹窗，清空地址
      this.foundRtspFlag = false
      this.adress = ''
    },
    handleClose() { // 关闭弹窗清空地址
      this.adress = ''
    },

    getOrgnk() {
      let params = {
        app_code: this.app_code
      }
      let success = (res) => {
        this.orgDlist = res.data.children
      };
      this.$ajax.get('api/network/get_org_subject', { params, func: { success } })
    },
    handleChange(val) {
      this.valueData = val
    },
    get_schoolcode() {
      /*获取学校教育局 */
      let params = {
        app_code: this.app_code,
      };
      let success = (res) => {
        // console.log(res, 'pppp')
        this.schoolcodeData = res.data;
      };
      this.$ajax.get("api/group/get_platform_org", {
        params,
        func: { success },
      });
    },
    handleSelectionChange(val) {
      this.ids = [];
      if (val.length > 0) {
        val.forEach((item) => {
          this.ids.push(item.id);
        });
      }
    },

    searchFunc() {
      this.listParam.platform_id = this.platform_id;
      this.$store.state.checkLevel && (this.listParam.grade_id = this.valueData[0]);
      this.$store.state.checkLevel && (this.listParam.subject_id = this.valueData[1]);
      this.listParam.keyword = this.keyword;
      this.listParam.live_type = this.live_type;
      this.listParam.page_index = 1;
      if (!is_empty(this.dataTime)) {
        this.listParam.startDateTime = this.dataTime[0];
        this.listParam.endDateTime = this.dataTime[1];
      } else {
        this.listParam.startDateTime = "";
        this.listParam.endDateTime = "";
      }
      this.getList();
    },
    reset() {
      this.valueData = [];
      this.platform_id = null;
      this.keyword = "";
      this.live_type = "-1";
      this.dataTime = [];
      this.listParam.startDateTime = "";
      this.listParam.endDateTime = "";
      this.listParam = {
        platform_id: undefined,
        live_type: "-1",
        keyword: undefined,
        page_index: 1,
        page_size: 10,
      };
      this.getList();
    },
    importClass() {
      this.$router.push("/resources/live/live-import");
    },
    broadcast() {
      this.$router.push("/resources/live/live-broadcast");
    },
    // 序号
    typeIndex(index) {
      return (
        index + (this.listParam.page_index - 1) * this.listParam.page_size + 1
      );
    },
    getList() {
      this.loading.status = true;

      let success = (data) => {

        this.loading.status = false;
        this.listData = data.data.data;

        this.total_number = data.data.data_sum;
      };
      let fail = (data) => {
        this.loading.status = false;
        this.$message.error(data.msg);
      };
      //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
      this.$ajax.get("api/live/live_list", {
        params: this.listParam,
        func: { success: success, fail: fail },
      });
    },
    /**
     * 确认停止当前直播
     * @param {Object} obj 当前直播信息
     */
    stopConfirm(obj) {
      let yes = (res) => {
        this.stopLive(obj.id);
      };
      let cancel = (res) => { };

      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt: "确定将 " + obj.name + " 停止吗？",
      });
    },
    /**
     * 停止当前直播
     * @param {Number} id 直播 id
     */
    stopLive(id) {
      let success = (res) => {
        this.$message.success(res.msg);
        setTimeout(() => {
          this.getList();
        }, 1000);
      };
      let params = { id };

      this.$ajax.put("api/live/stop_live", params, {
        func: { success: success },
      });
    },
    delete_confirm(obj) {
      let yes = (data) => {
        this.delete(obj.id, 0);
      };
      let cancel = (data) => { };
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt: "确定将 " + obj.name + " 删除吗？",
      });
    },
    delete(id, status) {
      let success = (data) => {
        this.$message.success(data.msg);

        if (this.listData.length - 1 === 0) {
          if (this.listParam.page_index > 1) {
            this.listParam.page_index--;
          } else {
            this.listParam.page_index = 1;
          }
        }

        this.getList();
      };
      this.$ajax.delete("api/live/live", {
        params: { liveid: id, status: status },
        func: { success: success },
      });
    },
    delAllLiveplay() {
      // 批量删除直播列表
      if (this.ids.length <= 0) {
        this.$message.warning("请选择要删除的直播");
        return false;
      }
      const cancel = (res) => { };
      const yes = (res) => {
        this.listData.forEach((item, index) => {
          this.ids.forEach((itm, idx) => {
            if (item.id == itm) {
              this.delete(itm, 0);
            }
          });
        });
      };

      this.e_confirm({ yes, cancel, txt: "确定要删除选中的直播吗？" });
    },
    handleSizeChange(val) {
      this.listParam.page_index = 1;
      this.listParam.page_size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listParam.page_index = val;
      this.getList();
    },
    toLink(link) {
      this.$router.push(link);
    },
    pushLow(data) {
      /*推下级 */
      this.pushLowObj = data;
      this.pushLowStatus = null;
      this.pushLowFlag = true;
    },
    videoView(item) {
      let userAgent = navigator.userAgent
      if (userAgent.indexOf('Firefox') > -1) {
        let num = userAgent.toLowerCase().match(/firefox\/([\d.]+)/)[1].split('.')[0]
        if (num < 74) {
          this.$message.warning(`当前浏览器版本为火狐${num}，请升级到74版本以上`)
        }
      }

      this.isActive = false;
      this.playerOption.url = item.play_url;
      this.playerOption.status_stream = item.status_stream == "1" ? true : false;
      this.playerOption.status_stream_audio = item.status_stream_audio == "1" ? true : false;
      this.showVideoPlayer = true;
    },
    viewClose() {
      this.showVideoPlayer = false;
      this.isActive = true;
    },
    pushActive(flag) {
      /*推下级执行 */
      if (flag) {
        if (this.selSchoolList.length <= 0) {
          this.$message.error("请选择要推送的下级");
          return;
        }
        let params = {
          id: [],
          res_type: "live",
          school_id: "",
          push_type: 2,
        };
        if (this.pushLowStatus) {
          params.id = this.ids;
        } else {
          params.id.push(this.pushLowObj.id);
        }
        let arr = [];
        this.selSchoolList.forEach((item) => {
          arr.push(item.id);
        });
        params.school_id = arr.join();
        const success = (res) => {
          this.pushLowHide();
          this.ids = [];
          this.getList();
        };
        this.$ajax.post("api/level/push_data", params, {
          func: { success: success },
        });
      } else {
        this.pushLowHide();
      }
    },
    pushLowAll() {
      /*批量推下级 */
      if (this.ids.length <= 0) {
        this.$message.error("请选择要推送的选项");
        return;
      }
      this.pushLowStatus = 1;
      this.pushLowFlag = true;
    },
    getPushLowList(list) {
      /*获取组件传递列表 */
      this.selSchoolList = list;
    },
    pushLowHide() {
      /*推下级窗口隐藏 */
      this.pushLowObj = null;
      this.pushLowFlag = false;
    },
    platform_parent() {
      /*获取可推送上级 */
      const success = (res) => {
        if (!is_empty(res.data)) {
          this.platform = res.data.name;
          this.pid = res.data.id;
          this.$forceUpdate(); //强制渲染
        }
      };
      this.$ajax.get("api/level/platform_parent", {
        params: {},
        func: { success: success },
      });
    },
    pushUp(id) {
      let params = {
        id: id,
        res_type: "live",
        school_id: this.pid,
        push_type: 1,
      };
      const success = (res) => {
        this.$message.success(res.msg);
        this.ids = [];
        this.getList();
      };
      this.$ajax.post("api/level/push_data", params, {
        func: { success: success },
      });
    },
    pushTop(id) {
      let params = {
        live_id: id,
      };
      let success = (res) => {
        this.$message.success(res.msg);
        this.getList();
      };
      this.$ajax.post("api/live/live_push", params, { func: { success } });
    },
    pushUpTrigger(data) {
      if (this.$store.state.checkLevel) {
        let title = `是否要将资源推送至${this.platform}？（需经过审核）`;
        this.$confirm(title, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.pushTop(data.id);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消推送",
            });
          });
      } else {
        let title = `是否要将资源推送至${this.platform}？（需经过审核）`;
        this.$confirm(title, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            if (data) {
              let ids = [data.id];
              this.pushUp(ids);
            } else {
              this.pushUp(this.ids);
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消推送",
            });
          });
      }
    },
    pushUpAll() {
      /*批量推上级 */
      if (this.ids.length <= 0) {
        this.$message.error("请选择要推送的选项");
        return;
      }
      this.pushUpTrigger();
    },
  },
  components: {
    pushLowWin,
    // flvPlayer,
    flvdplayer,
    webRtcPlayer
  },
};
</script>
<style lang="scss">
.zh-livePlay-list {
  .el-table__body-wrapper table tbody {
    td:nth-child(7) {
      padding: 0;
    }
  }

  .open-width {
    .el-date-editor {
      width: 100%;
      vertical-align: middle;
    }
  }

  .masking {
    display: block;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    transition: 0.5s;
    background: rgba(0, 0, 0, 0.3);
    z-index: 4;

    .maskingBox {
      position: absolute;
      top: 20%;
      left: 50%;
      width: 800px;
      margin-left: -400px;
      background: #fff;
    }

    .masking_h {
      padding: 10px 15px;
      background: #348efc;
      text-align: center;
      text-align-last: justify;

      >span,
      >i {
        font-size: 16px;
        text-align-last: initial;
        display: inline-block;
        vertical-align: middle;
        color: #fff;
      }

      >i {
        cursor: pointer;
      }
    }

    .masking_cc {
      height: 450px;
      padding: 15px;
    }
  }

  .activeLive {
    opacity: 0;
    visibility: hidden;
  }

  .rtspText {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box; //作为弹性伸缩盒子模型显示。
    -webkit-box-orient: vertical; //设置伸缩盒子的子元素排列方式--从上到下垂直排列
    -webkit-line-clamp: 3; //显示的行
  }

  .copyText {
    position: absolute;
    bottom: -99999px;
    left: 0;
    opacity: 0;
  }
}
</style>
